#include "wifi.h"
#include "disp.h"
#include "bs818.h"
#include "task.h"
#include "bitmap.h"
#include "WiFiManager.h"
#include "ESP8266WiFiMulti.h"
#include "EEPROM.h"
#include "ui.h"
#include "blinkercfg.h"
#include "eeconfig.h"

uint8_t WIFI_STATE  = 0;
uint8_t smart_config = 0;
extern uint8_t force_request;
extern uint8_t font_color[3];
char wifi_ssid[20];
char wifi_pwd[20];
char weather_key[20];
char weather_city[20];
char blinker_key[20];
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
WiFiManager wm;
ESP8266WiFiMulti wifi_multi;
WiFiManagerParameter set_weather_key("weather_key", "WeatherKey", NULL, 20);
WiFiManagerParameter set_blinker_key("blinker_key", "BlinkerKey", NULL, 20);
WiFiManagerParameter set_city("city", "City", NULL, 20);

void wifiCheckTask(void)
{
    if(WiFi.status() == WL_CONNECTED)
    {
        WIFI_STATE = 1;
        Serial.println("wifi connected");
    }
    else
    {
        WIFI_STATE = 0;
        Serial.println("wifi disconnected");
    }
}

uint8_t firmware_run = 0;
void firmwareUpdate(void)
{
    static uint8_t cnt = 0;
    if(WIFI_STATE)
    {
        if(key_status == KEY_R_L || cnt == 1)
        {
            if(cnt == 0)
            {
                cnt = 1;
                taskStop();
                firmware_run = 1;
                MDNS.begin("pixelclock");
                httpUpdater.setup(&httpServer);
                httpServer.begin();
                MDNS.addService("http", "tcp", 80);
            }
            else
            {                
                if(key_status == KEY_MENU)
                {
                    taskStart();
                    cnt = 0;
                    firmware_run = 0;
                    return;
                }
                updateDisp();
                httpServer.handleClient();
                MDNS.update();
            }
        }
    }
}

void initWiFi(void)
{
    wm.setShowPassword(true);
    wm.setBreakAfterConfig(true);
    wm.setSaveConfigCallback(saveConfig);
    wm.setDebugOutput(false);
    wm.setWiFiAutoReconnect(true);
    wm.addParameter(&set_blinker_key);
    wm.addParameter(&set_weather_key);
    wm.addParameter(&set_city);

    readConfig();
}

void webConfig(void)
{
    static uint8_t web_flag = 0;
    uint8_t cnt = 0;
    char color[4] = {0, 0, 0, 0};

    if(key_status == KEY_M_L || web_flag == 1)
    {
        key_status = KEY_NONE;
        // wm.disconnect();
        taskStop();
        wifiDisp(WIFI_CONNECTING);
        set_blinker_key.setValue(blinker_key, 20);
        set_weather_key.setValue(weather_key, 20);
        set_city.setValue(weather_city, 20);
        wm.startConfigPortal("PixelClock", "12345678");
        web_flag = 0;
        cnt = 7;
        while(cnt--)
        {
            wifiDisp(WIFI_CONNECTED);
            delay(70);
        }
        clearScreen();
        drawString("Restart...", 0, 0, 0x0064C8);
        sendToScreen();
        delay(1000);
        ESP.restart();
    }
}
